import re

"""
统计happy.txt文件中每个单词的出现次数，并打印出现次数最多的十个单词
"""


def find_words(param: str) -> list:
    return re.findall(r'[a-zA-Z]+', param)


def calc_count(param: list) -> None:
    # 空字典存储
    dict_words = dict()
    for word in param:
        if word in dict_words.keys():
            dict_words[word] += 1
        else:
            dict_words[word] = 1
    # 返回次数
    print(dict_words)
    # 排序
    sorted_dict_words = sorted(dict_words.items(), key=lambda x: x[1], reverse=True)
    print([sorted_dict_words[i][0] for i in range(10)])


if __name__ == '__main__':
    try:
        with open(file='./happy.txt', mode='r', encoding='gbk') as f:
            file = f.read()
            list_words = find_words(file)
            # 打印次数及出现次数最多的前10个单词
            calc_count(list_words)

    except IOError as e:
        print('Error：' + str(e))
